package org.jeecg.modules.zhoupackage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.modules.gwcjava.jiekou.entity.MlccUserInfo;
import org.jeecg.modules.zhouAdmin.admin.fabeicCenter.mapper.MyMlccFabricLadderPriceMapper;
import org.jeecg.modules.zhouAdmin.admin.fabeicCenter.pojo.MlccFabricLadderPrice;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.mapper.MyMlccCompanyInfoMapper;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.pojo.MlccCompanyInfo;
import org.jeecg.modules.zhoupackage.mapper.*;
import org.jeecg.modules.zhoupackage.pojo.*;
import org.jeecg.modules.zhoupackage.service.ICartService;
import org.jeecg.modules.zhoupackage.util.FabricUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 购物车Service
 *
 * @author zxl
 * @since 20200922
 */
@Service
public class CartServiceImpl implements ICartService {

    @Autowired
    MlccCartInfoMapper mapper;

    @Autowired
    CartMlccUserInfoMapper userInfoMapper;

    @Autowired
    MlccFabricInfoMapper fabricInfoMapper;

    @Autowired
    MlccGroupInfoMapper groupInfoMapper;

    @Autowired
    FabricUtil fabricUtil;

    @Autowired
    MyMlccFabricOrderinfoMapper fabricOrderinfoMapper;

    @Autowired
    MlccFabricColorMapper fabricColorMapper;

    @Autowired
    MyMlccCourierInfoMapper courierInfoMapper;

    @Autowired
    MyMlccstoreMapper storeMapper;

    @Autowired
    MlccCartInfoMapper cartInfoMapper;

    @Autowired
    MyMlccFabricLadderPriceMapper fabricLadderPriceMapper;

    @Autowired
    MyMlccCompanyInfoMapper companyInfoMapper;

    @Autowired
    MyTrackingOrderMapper trackingOrderMapper;

    @Autowired
    MyMlccStoreAddressMapper storeAddressMapper;

    /**
     * 添加购物车
     *
     * @param cart
     * @return
     */
    @Override
    public int insertCart(MlccCartInfo cart, String token) {
        double zhekou = 1L;
        /*根据Token获取当前登录用户*/
        MlccUserInfo userInfo = getUserByToken(token);
        if (userInfo == null) return -1;
        cart.setUserId(userInfo.getId() + "").setCreateBy(userInfo.getUsername()).setUpdateBy(userInfo.getUsername());
        /*查询面料的价格*/
        MlccFabricInfo fabricInfo = fabricInfoMapper.selectById(cart.getFabricId());

        fabricUtil.addPrice(fabricInfo, cart.getBuyNumber());
        // 计算这个购物车的价格
        BigDecimal amount = fabricInfo.getFabricPrice().multiply(new BigDecimal(cart.getBuyNumber()));
//        double last = amount.setScale(2, BigDecimal.ROUND_FLOOR).doubleValue();
        // 获取面料折扣
        zhekou = fabricUtil.userFabricDiscount(userInfo.getId() + "", fabricInfo.getGroupId());
        BigDecimal multiply = amount.multiply(new BigDecimal(zhekou));
        cart.setTotalAmount(multiply.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "");
        /*如果面料表的组ID为空，说明有自己的单价，直接计算*//*
        if (fabricInfo.getGroupId() == null) {
            double amount = cart.getBuyNumber() * fabricInfo.getFabricPrice().doubleValue();
            cart.setTotalAmount(amount + "");
        } else {
            *//*否则进入面料组表获取单价*//*
            MlccGroupInfo groupInfo = groupInfoMapper.selectById(fabricInfo.getGroupId());
            double amount = cart.getBuyNumber() * groupInfo.getPrice().doubleValue();
            cart.setTotalAmount(amount + "");
        }*/
        int insert = mapper.insert(cart);
        return insert;
    }

    /**
     * 根据token获取用户信息
     *
     * @param token
     * @return
     */
    @Override
    public MlccUserInfo getUserByToken(String token) {
        QueryWrapper<MlccUserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("token", token);
        return userInfoMapper.selectOne(wrapper);
    }

    /**
     * 根据购物车id逻辑删除购物车
     *
     * @param id 购物车id
     */
    @Override
    public int removeCart(int id) {
        MlccCartInfo cartInfo = mapper.selectById(id);
        int result = mapper.deleteById(id);
        /*if (result > 0) {
            // 恢复库存
            MlccFabricInfo fabricInfo2 = fabricInfoMapper.selectById(cartInfo.getFabricId());
            *//*fabricInfo2.setInventory(fabricInfo2.getInventory() + cartInfo.getBuyNumber());*//*
            fabricInfoMapper.updateById(fabricInfo2);
        }*/
        return result;
    }

    /**
     * 根据token获取当前用户购物车列表
     *
     * @param token 令牌
     */
    @Override
    public List<CartEntity> getCartList(String token) {
        double zhekou = 1;
        BigDecimal price = new BigDecimal(0);
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        List<CartEntity> cartList = mapper.getCartList(token);
        List<CartEntity> entities = fabricUtil.addPrice(cartList);
        if (entities != null && entities.size() > 0) {
            for (CartEntity cart : entities) {
                MlccFabricInfo fabricInfo = fabricInfoMapper.selectById(cart.getFabricId());
                price = price.add(new BigDecimal(Double.valueOf(cart.getTotalAmount())));
                if (fabricInfo != null && fabricInfo.getGroupId() != null) {
                    // 获取面料折扣
                    zhekou = fabricUtil.userFabricDiscount(userDetail.getId() + "", fabricInfo.getGroupId());
                    cart.setDiscount(zhekou);
                }
            }

            for (CartEntity entity : entities) {
                entity.setZzzp(price.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "");
            }
        }
        return entities;
    }

    /**
     * 购物车购买数量加一
     *
     * @param cartid 购物车id
     */
    @Override
    public int incrByNum(int cartid, String token) {
        double zhekou = 1;
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        MlccCartInfo cartInfo = mapper.selectById(cartid);
        cartInfo.setBuyNumber(cartInfo.getBuyNumber() + 1);
        /*判断面料的库存是否足够*/
        MlccFabricInfo fabricInfo = fabricInfoMapper.selectById(cartInfo.getFabricId());
        // 获取面料价格
        fabricUtil.addPrice(fabricInfo, cartInfo.getBuyNumber());

        // 计算价格
        BigDecimal amount = fabricInfo.getFabricPrice().multiply(new BigDecimal(cartInfo.getBuyNumber()));
//        BigDecimal scale = new BigDecimal(amount).setScale(2, BigDecimal.ROUND_FLOOR);
        // 获取面料折扣
        zhekou = fabricUtil.userFabricDiscount(userDetail.getId() + "", fabricInfo.getGroupId());
        BigDecimal multiply = amount.multiply(new BigDecimal(zhekou));
        cartInfo.setTotalAmount(multiply.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "");
        /*Double inventory = fabricInfo.getInventory();*/
        /*if (inventory >= cartInfo.getBuyNumber()) {*/
        /*修改总金额*/
        /*如果面料表的组ID为空，说明有自己的单价，直接计算*/
        /*if (fabricInfo.getGroupId() == null) {
            double amount = cartInfo.getBuyNumber() * fabricInfo.getFabricPrice().doubleValue();
            BigDecimal scale = new BigDecimal(amount).setScale(2, BigDecimal.ROUND_FLOOR);
            cartInfo.setTotalAmount(scale.doubleValue() + "");
        } else {
            *//*否则进入面料组表获取单价*//*
            MlccGroupInfo groupInfo = groupInfoMapper.selectById(fabricInfo.getGroupId());
            double amount = cartInfo.getBuyNumber() * groupInfo.getPrice().doubleValue();
            BigDecimal scale = new BigDecimal(amount).setScale(2, BigDecimal.ROUND_FLOOR);
            cartInfo.setTotalAmount(scale.doubleValue() + "");
        }*/
        int result = mapper.updateById(cartInfo);
            /*if (result > 0) {
                // 面料减少库存
                MlccFabricInfo fabricInfo2 = fabricInfoMapper.selectById(cartInfo.getFabricId());
                fabricInfo2.setInventory(fabricInfo2.getInventory() - 1);
                fabricInfoMapper.updateById(fabricInfo2);
            }*/
        return result;
        /*} else {
         *//*说明库存数量不够不能添加了*//*
            return -1;
        }*/
    }

    /**
     * 购物车购买数量减一
     *
     * @param cartid 购物车id
     * @param token  令牌
     */
    @Override
    public int decrByNum(int cartid, String token) {
        double zhekou = 1;
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);

        MlccCartInfo cartInfo = mapper.selectById(cartid);
        cartInfo.setBuyNumber(cartInfo.getBuyNumber() - 1);
        /*判断面料的库存是否足够*/
        MlccFabricInfo fabricInfo = fabricInfoMapper.selectById(cartInfo.getFabricId());
        if (cartInfo.getBuyNumber() >= 1) {
            // 获取面料价格
            fabricUtil.addPrice(fabricInfo, cartInfo.getBuyNumber());
            BigDecimal amount = fabricInfo.getFabricPrice().multiply(new BigDecimal(cartInfo.getBuyNumber()));
//            BigDecimal scale = new BigDecimal(amount).setScale(2, BigDecimal.ROUND_FLOOR);
            // 获取面料折扣
            zhekou = fabricUtil.userFabricDiscount(userDetail.getId() + "", fabricInfo.getGroupId());
            BigDecimal multiply = amount.multiply(new BigDecimal(zhekou));
            cartInfo.setTotalAmount(multiply.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "");
            /*修改总金额*/
            /*如果面料表的组ID为空，说明有自己的单价，直接计算*/
            /*if (fabricInfo.getGroupId() == null) {
                double amount = cartInfo.getBuyNumber() * fabricInfo.getFabricPrice().doubleValue();
                BigDecimal scale = new BigDecimal(amount).setScale(2, BigDecimal.ROUND_FLOOR);
                cartInfo.setTotalAmount(scale.doubleValue() + "");
            } else {
                *//*否则进入面料组表获取单价*//*
                MlccGroupInfo groupInfo = groupInfoMapper.selectById(fabricInfo.getGroupId());
                double amount = cartInfo.getBuyNumber() * groupInfo.getPrice().doubleValue();
                BigDecimal scale = new BigDecimal(amount).setScale(2, BigDecimal.ROUND_FLOOR);
                cartInfo.setTotalAmount(scale.doubleValue() + "");
            }*/
            int result = mapper.updateById(cartInfo);
            /*if (result > 0) {
                // 恢复库存
                MlccFabricInfo fabricInfo2 = fabricInfoMapper.selectById(cartInfo.getFabricId());
                fabricInfo2.setInventory(fabricInfo2.getInventory() + 1);
                fabricInfoMapper.updateById(fabricInfo2);
            }*/
            return result;
        } else {
            /*说明库存数量不够不能添加了*/
            return -1;
        }
    }

    /**
     * 购物车界面 修改面料购买米数
     *
     * @param cartid 购物车ID
     * @param buyNum 购买数量
     */
    @Override
    public int changeBuyNumber(String cartid, Double buyNum, String token) {
        double zhekou = 1;
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);

        MlccCartInfo cartInfo = mapper.selectById(cartid);
        // 修改数量之前和修改数量之后的差额 正数是减少，则恢复库存，加操作；负数是增加购买，减库存，减操作
        double revelation = cartInfo.getBuyNumber() - buyNum;
        if (revelation == 0) {
            // 结束了，什么也没有发生
            return -5;
        }
        /*判断面料的库存是否足够*/
        MlccFabricInfo fabricInfo = fabricInfoMapper.selectById(cartInfo.getFabricId());
        /*if (fabricInfo.getInventory() >= buyNum) {*/
        cartInfo.setBuyNumber(buyNum);
        /*修改总金额*/
        /*如果面料表的组ID为空，说明有自己的单价，直接计算*/
        fabricUtil.addPrice(fabricInfo, cartInfo.getBuyNumber());
        BigDecimal amount = fabricInfo.getFabricPrice().multiply(new BigDecimal(cartInfo.getBuyNumber()));
//        BigDecimal scale = new BigDecimal(amount).setScale(2, BigDecimal.ROUND_FLOOR);
        // 获取面料折扣
        zhekou = fabricUtil.userFabricDiscount(userDetail.getId() + "", fabricInfo.getGroupId());
        BigDecimal multiply = amount.multiply(new BigDecimal(zhekou));
        cartInfo.setTotalAmount(multiply.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "");
       /* if (fabricInfo.getGroupId() == null) {
            double amount = cartInfo.getBuyNumber() * fabricInfo.getFabricPrice().doubleValue();
            BigDecimal scale = new BigDecimal(amount).setScale(2, BigDecimal.ROUND_FLOOR);
            cartInfo.setTotalAmount(scale.doubleValue() + "");
        } else {
            *//*否则进入面料组表获取单价*//*
            MlccGroupInfo groupInfo = groupInfoMapper.selectById(fabricInfo.getGroupId());
            double amount = cartInfo.getBuyNumber() * groupInfo.getPrice().doubleValue();
            BigDecimal scale = new BigDecimal(amount).setScale(2, BigDecimal.ROUND_FLOOR);
            cartInfo.setTotalAmount(scale.doubleValue() + "");
        }*/
        int result = mapper.updateById(cartInfo);
            /*if (result > 0) {
                // 恢复库存
                MlccFabricInfo fabricInfo2 = fabricInfoMapper.selectById(cartInfo.getFabricId());
                *//*fabricInfo2.setInventory(fabricInfo2.getInventory() + revelation);*//*
                fabricInfoMapper.updateById(fabricInfo2);
            }*/
        return result;
        /*} else {
         *//*说明库存数量不够不能添加了*//*
            return -1;
        }*/
    }

    /**
     * 购物车结算界面数据显示
     *
     * @param token
     * @param cartIds
     * @return
     */
    @Override
    public JSONObject settlement(String token, int[] cartIds) {
        MlccUserInfo userDetail = getUserDetail(token);
        if (null == userDetail) {
            return null;
        }
        JSONObject jsonObject = new JSONObject();
        double totalAmount = 0;
        List<CartEntity> cartList = getCartList(token);
        List<CartEntity> result = new ArrayList<>();
        if (cartList != null && cartIds != null) {
            for (CartEntity entity : cartList) {
                for (int j = 0; j < cartIds.length; j++) {
                    if (cartIds[j] == entity.getId()) {
                        result.add(entity);
                        totalAmount += Double.valueOf(entity.getTotalAmount());
                    }
                }
            }
        }
        jsonObject.put("data", result);
        jsonObject.put("totalAmount", totalAmount);
        jsonObject.put("accountBalance", userDetail.getAccountBalance());
        return jsonObject;
    }

    /**
     * 根据token获取用户详情
     *
     * @param token
     * @return
     */
    @Override
    public MlccUserInfo getUserDetail(String token) {
        QueryWrapper<MlccUserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("token", token);
        return userInfoMapper.selectOne(wrapper);
    }

    /**
     * 面料订单详情
     *
     * @param orderSn 面料订单号
     * @return
     */
    @Override
    public MlccFabricOrderinfo getFabricOrderDetail(String orderSn) {
        //if (!fabricUtil.checkToken(token)) return null;
        QueryWrapper<MlccFabricOrderinfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccFabricOrderinfo fabricOrderinfo = fabricOrderinfoMapper.selectOne(wrapper);

        // 查询支付时间
        QueryWrapper<MlccTrackingOrder> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("order_sn", orderSn).eq("order_status", 1);
        MlccTrackingOrder trackingOrder = trackingOrderMapper.selectOne(wrapper2);
        if (trackingOrder != null) {
            fabricOrderinfo.setPayTime(trackingOrder.getCreateTime());
        }

        // 查询这个订单的用户信息
        MlccUserInfo mlccUserInfo = userInfoMapper.selectById(fabricOrderinfo.getUserId());
        if (mlccUserInfo != null) {
            // 获取下单员工信息
            fabricOrderinfo.setEmpName(mlccUserInfo.getRealname()).setEmpPhone(mlccUserInfo.getPhone());
        }
        // 查询这个订单的客户折扣
        String discount = cartInfoMapper.getDiscount(mlccUserInfo.getDiscount(), 0);
        if (discount == null) {
            discount = "1";
        }
        if (fabricOrderinfo != null) {
            // 查询快递信息
            MlccCourierInfo mlccCourierInfo = courierInfoMapper.selectById(fabricOrderinfo.getCourierId());
            if (mlccCourierInfo != null) {
                fabricOrderinfo.setCourierName(mlccCourierInfo.getCourierName());
            }

            if (fabricOrderinfo.getCartId() != null) {
                List<String> cartids = Arrays.asList(fabricOrderinfo.getCartId().split(","));
                QueryWrapper<MlccCartInfo> wrapper1 = new QueryWrapper<>();
                wrapper1.in("id", cartids);
                List<MlccCartInfo> cartInfos = mapper.selectList(wrapper1);// 面料订单下的所有购物车
                fabricOrderinfo.setCartInfoList(cartInfos);
                // 查询门店名称
                MlccStoreInfo storeInfo = storeMapper.selectById(fabricOrderinfo.getStoreId());
                fabricOrderinfo.setStoreName(storeInfo.getStoreName());

                // 获取客户编号和客户名称（也就是获取门店对应的公司编号和名称）
                if (storeInfo != null) {
                    MlccCompanyInfo companyInfo = companyInfoMapper.selectById(storeInfo.getCompanyId());
                    if (companyInfo != null) {
                        fabricOrderinfo.setCompanyName(companyInfo.getCompanyName()).setCompanyCode(companyInfo.getCompanyCode());
                    }
                }

                if (cartInfos != null && cartInfos.size() > 0) {
                    // 查询购物车下面的所有面料信息
                    for (MlccCartInfo cartInfo : cartInfos) {
                        double zhekou = 1;
                        MlccFabricInfo fabricInfo = fabricInfoMapper.selectById(cartInfo.getFabricId());
                        // 重新查询面料的价格(拿到了标准单价)
                        fabricInfo = fabricUtil.addPrice(fabricInfo, cartInfo.getBuyNumber());
                        // 有系列才有折扣，上面已经拿到了面料的价格
                        if (fabricInfo != null && fabricInfo.getGroupId() != null) {
                            // 获取面料折扣
                            zhekou = fabricUtil.userFabricDiscount(fabricOrderinfo.getUserId(), fabricInfo.getGroupId());
                            fabricInfo.setKehuzk(zhekou);
                            double afterPrice = fabricInfo.getFabricPrice().doubleValue() * fabricInfo.getKehuzk() * Double.valueOf(discount);
                            //折后单价保留两位小数
                            BigDecimal bigDecimal = new BigDecimal(afterPrice);
                            double v = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                            fabricInfo.setAfterPrice(v);
                            double lastPrice = new BigDecimal(v * cartInfo.getBuyNumber()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                            cartInfo.setTotalAmount(lastPrice + "");
                        } else {
                            // 说明是主推
                            fabricInfo.setAfterPrice(fabricInfo.getFabricPrice().doubleValue());
                        }
                        cartInfo.setFabricInfo(fabricInfo);
                    }
                }
            }
        }
        return fabricOrderinfo;
    }

    /**
     * 购物车更新备注
     *
     * @param id     购物车id
     * @param remark 备注
     */
    @Override
    public int updateRemark(String id, String remark) {
        MlccCartInfo mlccCartInfo = cartInfoMapper.selectById(id);
        mlccCartInfo.setRemark(remark);
        return cartInfoMapper.updateById(mlccCartInfo);
    }

    /**
     * 获取面料的阶梯价格
     *
     * @param id 面料ID
     */
    @Override
    public List<MlccFabricLadderPrice> listFabricPrice(String id) {
        MlccFabricInfo fabricInfo = fabricInfoMapper.selectById(id);
        if (fabricInfo != null) {
            if (fabricInfo.getGroupId() != null) {
                QueryWrapper<MlccFabricLadderPrice> wrapper = new QueryWrapper<>();
                wrapper.eq("group_id", fabricInfo.getGroupId());
                return fabricLadderPriceMapper.selectList(wrapper);
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 根据门店标号获取门店地址
     *
     * @param storeCode 门店编号
     */
    @Override
    public List<MlccStoreAddress> addressList(String storeCode) {
        QueryWrapper<MlccStoreInfo> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("store_code", storeCode);
        MlccStoreInfo storeInfo = storeMapper.selectOne(wrapper1);
        MlccCompanyInfo companyInfo = companyInfoMapper.selectById(storeInfo.getCompanyId());
        QueryWrapper<MlccStoreAddress> wrapper = new QueryWrapper<>();
        wrapper.eq("company_id", companyInfo.getId());
        return storeAddressMapper.selectList(wrapper);
    }
}
